package com.resume.aipeople.service.ai;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.regex.Pattern;

@Service
@Slf4j
public class AISkillService {
    
    private final Map<String, String> emotionKeywords;
    private final List<String> creativePrompts;
    
    public AISkillService() {
        // 初始化情感关键词
        emotionKeywords = new HashMap<>();
        emotionKeywords.put("happy", "开心,快乐,高兴,愉快,兴奋,喜悦");
        emotionKeywords.put("sad", "伤心,难过,失落,沮丧,悲伤,痛苦");
        emotionKeywords.put("angry", "生气,愤怒,烦躁,恼火,愤恨,暴躁");
        emotionKeywords.put("anxious", "焦虑,担心,紧张,不安,恐惧,害怕");
        emotionKeywords.put("confused", "困惑,疑惑,迷茫,不解,不明白");
        emotionKeywords.put("surprised", "惊讶,震惊,意外,吃惊,诧异");
        emotionKeywords.put("neutral", "平静,正常,一般,还好");
        
        // 初始化创作提示
        creativePrompts = Arrays.asList(
            "写一首关于{}的诗",
            "讲一个关于{}的故事",
            "用比喻的方式描述{}",
            "想象一下如果{}会说话",
            "为{}写一段独白"
        );
    }
    
    /**
     * 知识问答技能 - 基于角色背景提供专业回答
     */
    public String enhanceKnowledgeResponse(String basePrompt, String userMessage, String knowledgeBase) {
        StringBuilder enhancedPrompt = new StringBuilder(basePrompt);
        enhancedPrompt.append("\n知识问答。");
        if (knowledgeBase != null && !knowledgeBase.trim().isEmpty()) {
            enhancedPrompt.append("知识领域：").append(knowledgeBase);
        }
        
        return enhancedPrompt.toString();
    }
    
    /**
     * 情感感知技能 - 分析用户情感并给出适当回应
     */
    public String detectEmotion(String userMessage) {
        String message = userMessage.toLowerCase();
        
        for (Map.Entry<String, String> entry : emotionKeywords.entrySet()) {
            String[] keywords = entry.getValue().split(",");
            for (String keyword : keywords) {
                if (message.contains(keyword)) {
                    log.info("检测到情感: {} (关键词: {})", entry.getKey(), keyword);
                    return entry.getKey();
                }
            }
        }
        
        return "neutral";
    }
    
    public String enhanceEmotionalResponse(String basePrompt, String userMessage, String detectedEmotion) {
        StringBuilder enhancedPrompt = new StringBuilder(basePrompt);
        enhancedPrompt.append("\n情感回应。");
        enhancedPrompt.append("用户情感：").append(getEmotionDescription(detectedEmotion));
        
        return enhancedPrompt.toString();
    }
    
    /**
     * 创作技能 - 生成诗歌、故事等创意内容
     */
    public String enhanceCreativeResponse(String basePrompt, String userMessage) {
        StringBuilder enhancedPrompt = new StringBuilder(basePrompt);
        enhancedPrompt.append("\n创意表达。");
        
        return enhancedPrompt.toString();
    }
    
    /**
     * 记忆管理技能 - 维护对话上下文
     */
    public String enhanceMemoryResponse(String basePrompt, List<String> recentMessages) {
        StringBuilder enhancedPrompt = new StringBuilder(basePrompt);
        enhancedPrompt.append("\n记忆对话。");
        
        return enhancedPrompt.toString();
    }
    
    /**
     * 分析技能 - 提供深入的分析和见解
     */
    public String enhanceAnalysisResponse(String basePrompt, String userMessage) {
        StringBuilder enhancedPrompt = new StringBuilder(basePrompt);
        enhancedPrompt.append("\n分析思考。");
        
        return enhancedPrompt.toString();
    }
    
    /**
     * 智能技能选择 - 根据用户消息自动选择最合适的技能
     */
    public String selectBestSkill(String userMessage) {
        userMessage = userMessage.toLowerCase();
        
        // 检测创作请求
        if (containsCreativeRequest(userMessage)) {
            return "creative";
        }
        
        // 检测情感内容
        if (containsEmotionalContent(userMessage)) {
            return "emotion";
        }
        
        // 检测知识问答
        if (containsQuestionWords(userMessage)) {
            return "knowledge";
        }
        
        // 检测分析请求
        if (containsAnalysisRequest(userMessage)) {
            return "analyze";
        }
        
        // 默认使用记忆技能保持对话连贯性
        return "memory";
    }
    
    private boolean containsCreativeRequest(String message) {
        String[] creativeWords = {"写", "创作", "诗", "故事", "歌", "想象", "编", "作诗"};
        return Arrays.stream(creativeWords).anyMatch(message::contains);
    }
    
    private boolean containsEmotionalContent(String message) {
        return emotionKeywords.values().stream()
                .anyMatch(keywords -> Arrays.stream(keywords.split(","))
                        .anyMatch(message::contains));
    }
    
    private boolean containsQuestionWords(String message) {
        String[] questionWords = {"什么", "为什么", "怎么", "如何", "哪", "是否", "能否", "可以", "？", "吗"};
        return Arrays.stream(questionWords).anyMatch(message::contains);
    }
    
    private boolean containsAnalysisRequest(String message) {
        String[] analysisWords = {"分析", "解释", "原因", "评价", "看法", "观点", "思考", "理解"};
        return Arrays.stream(analysisWords).anyMatch(message::contains);
    }
    
    private String getEmotionDescription(String emotion) {
        switch (emotion) {
            case "happy": return "开心快乐";
            case "sad": return "伤心难过";
            case "angry": return "生气愤怒";
            case "anxious": return "焦虑担心";
            case "confused": return "困惑疑惑";
            case "surprised": return "惊讶意外";
            default: return "平静正常";
        }
    }
} 